package com.sbxBase.service.impl;

import com.sbxBase.entity.FriendSearchUser;
import com.sbxBase.entity.Friends;
import com.sbxBase.mapper.FriendMapper;
import com.sbxBase.mapper.UserMapper;
import com.sbxBase.service.FriendsService;
import com.sbxBase.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.entity.sbxBase.User;
import com.common.utils.RequestUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FriendServiceImpl implements FriendsService {

    @Resource
    private UserService userService;

    @Resource
    private FriendMapper friendMapper;

    @Resource
    private UserMapper userMapper;


    @Override
    public Page<User> searchFriendsPage(FriendSearchUser friendSearchUser) {

        if (StringUtils.isEmpty(friendSearchUser.getPageIndex()) || StringUtils.isEmpty(friendSearchUser.getPageSize())) {
            friendSearchUser.setPageIndex(1);
            friendSearchUser.setPageSize(10);
        }

        User user = new User();
        BeanUtils.copyProperties(friendSearchUser,user);
        user.setNickName(user.getUserName());

        Page<User> userPage = userService.getUserPage(user, friendSearchUser.getPageIndex(), friendSearchUser.getPageSize());

        String loginUserId = RequestUtil.getLoginUserId();


        if (Boolean.TRUE.equals(friendSearchUser.getOnFriend())) {

            List<Friends> friends = friendMapper.selectList(new LambdaQueryWrapper<Friends>().eq(Friends::getSelfId, loginUserId));
            if (CollectionUtils.isEmpty(friends)) {
                return new Page<User>();
            }
            List<String> friendIds = friends.stream().map(Friends::getFriendId).collect(Collectors.toList());

            if (userPage.getTotal() != 0) {
                List<User> records = userPage.getRecords();
                userPage.setRecords(records.stream().map(x -> friendIds.contains(x.getId()) ? x : null).distinct().collect(Collectors.toList()));
            }
        }
        return userPage;
    }



    @Override
    @Transactional
    public void delFriends(String friendId) {
        friendMapper.deleteById(friendId);
    }


}
